import { SelectionRange } from "@/types/common";

export function useCursorManager() {
  let cursorSelectionRange: SelectionRange | null = null;

  // 获取光标选区
  function GetCursorSelectionRange(): SelectionRange | null {
    return cursorSelectionRange;
  }

  // 获取当前选区
  function GetLastSelection(): SelectionRange | null {
    return cursorSelectionRange;
  }

  // 聚焦
  function Focus(editor: HTMLElement) {
    editor.focus();
    const selection = document.getSelection();
    if (!selection) return;
    const selectionRange = GetCursorSelectionRange();
    if (!selectionRange) return;
    const range = document.createRange();
    range.selectNodeContents(editor);
    range.collapse(false);
    selection?.removeAllRanges();
    selection?.addRange(selectionRange.range);
  }

  // 更新选区
  function UpdateSelectionRange(sr: SelectionRange | null) {
    cursorSelectionRange = sr;
  }

  return {
    GetCursorSelectionRange,
    Focus,
    UpdateSelectionRange,
    GetLastSelection,
  };
}
